package org.iris.wiki

import net.mamoe.mirai.contact.Group
import net.mamoe.mirai.contact.Member
import net.mamoe.mirai.event.GlobalEventChannel
import net.mamoe.mirai.event.events.*
import net.mamoe.mirai.message.data.PlainText
import net.mamoe.mirai.utils.MiraiExperimentalApi
import org.iris.wiki.config.*
import org.iris.wiki.config.AliasConfig.ALIAS_MAP
import org.iris.wiki.config.AliasConfig.ALIAS_USER_MAP
import org.iris.wiki.data.ImagesData
import org.iris.wiki.data.SearchData
import org.iris.wiki.utils.HttpUtils
import org.iris.wiki.utils.MessageBuildUtils
import org.iris.wiki.utils.ParserUtils
import org.jsoup.Jsoup
import java.io.File
import java.nio.file.Paths
import java.util.*

internal object Listener {

    // 添加用户专有词典
    init {
        ALIAS_MAP.putAll(ALIAS_USER_MAP)
        val COMMANDS_LIST = setOf(
            CommandConfig.attribute,
            CommandConfig.dress,
            CommandConfig.dressLarge,
            CommandConfig.picLarge,
            CommandConfig.from,
            CommandConfig.tech,
            CommandConfig.evaluate,
            CommandConfig.equip,
            CommandConfig.wedding
        )
        for (list in COMMANDS_LIST) {
            CommandConfig.ALL_COMMAND.addAll(list)
        }
        CommandConfig.ALL_COMMAND.addAll(CommandConfig.voice_map.keys)
    }

    val channel = GlobalEventChannel.parentScope(Wiki)

    @OptIn(MiraiExperimentalApi::class)
    fun subscribe() {
        channel.subscribeAlways<GroupMessageEvent> {

            message.forEach {
                if (it is PlainText) {
                    var commandList = it.contentToString()
                        .lowercase(Locale.getDefault())
                        .split(Regex("[ ]+"))
                        .dropLastWhile { it.isEmpty() }
                        .toTypedArray()
                    if (commandList.isNotEmpty() && commandList[0] in CommandConfig.wiki) {
                        when (commandList.size) {
                            2 -> wiki(commandList, sender)
                            3 -> wiki(commandList, sender)
                            4 -> wiki(commandList, sender)
                            5 -> wiki(commandList, sender)
                            else -> group.sendMessage(MESSAGE_ERROR)
                        }
                    } else {
                        phraseCommand(it.contentToString(), sender)
                    }
//                    else if (commandList[0] in CommandConfig.group) {
//                        when (commandList.size) {
//                            2 -> group(commandList, sender)
//                            else -> group.sendMessage(MESSAGE_ERROR)
//                        }
//                    }

                }
            }
        }

        channel.subscribeAlways<NudgeEvent> {

            // 戳了戳事件
            if (this.target == bot && this.subject is Group) {
                if (CommandConfig.touch_first_param != "无" && CommandConfig.touch_second_param != "无") {
                    wiki(arrayOf("wiki", CommandConfig.touch_first_param, CommandConfig.touch_second_param), this.from as Member)
                }
            }
        }

        channel.subscribeAlways<MemberJoinRequestEvent>{
            // 入群信息
            var ivar = message.split('：').last()
            println("入群申请=========")
            println(ivar)
            if (groupId == 1056651973L && (SHIP_LIST.contains(ivar) || ALIAS_MAP.containsKey(ivar))) {
                accept()
            }
//            else if (groupId != 1056651973L) {
//                // 韩度群号
//                accept()
//            }
        }

        channel.subscribeAlways<BotInvitedJoinGroupRequestEvent>{
            // 被邀请入群
            accept()
        }

        channel.subscribeAlways<NewFriendRequestEvent> {
            // 好友申请
            val ivar = message.split('：').last()
            println("好友申请=========")
            println(ivar)
            if (ivar == "0827") {
                accept()
            }
        }


    }


    suspend fun phraseCommand(msg: String, sender: Member) {
        if (WikiConfig.command_parse_on) {
            var text = msg.lowercase(Locale.getDefault())
                .replace(Regex("[ ]+"), "")
            val commandList = arrayOf("", "", CommandConfig.attribute.first())
            for (wiki in CommandConfig.wiki) {
                if (text.startsWith(wiki)) {
                    text = text.removeRange(0, wiki.length)
                    commandList[0] = wiki
                    break
                }
            }

            if (commandList[0] in CommandConfig.wiki) {
                if (ALIAS_MAP.contains(text) || NAME_LIST.contains(text)) {
                    // 单词条
                    commandList[1] = text
                } else {
                    // 双词条
                    for (command in CommandConfig.ALL_COMMAND) {
                        if (text.endsWith(command)) {
                            text = text.substring(0, text.length - command.length)
                            commandList[2] = command
                            break
                        } else if (text.startsWith(command)) {
                            text = text.removeRange(0, command.length)
                            commandList[2] = command
                            break
                        }
                    }
                    commandList[1] = text
                }
                wiki(commandList, sender, false)
            }
        }
    }


    /**
     * 群攻略
     */
//    suspend fun group(commandList: Array<String>, sender: Member) {
//        when {
//            commandList[1] in arrayOf("目录") -> sender.group.sendMessage(
//                MessageBuildUtils.build(
//                    sender,
//                    TextData("本群攻略目录（腾讯文档）: https://docs.qq.com/doc/DV3ZiV3RSY01IY2ho"),
//                    commandList.toList()
//                )
//            )
//            commandList[1] in arrayOf("日历") -> sender.group.sendMessage(
//                MessageBuildUtils.build(
//                    sender,
//                    TextData("日历（腾讯文档）: https://docs.qq.com/sheet/DV1FQU0xwZ2tLRWFB"),
//                    commandList.toList()
//                )
//            )
//            commandList[1] in arrayOf("科技表") -> sender.group.sendMessage(
//                MessageBuildUtils.build(
//                    sender,
//                    TextData("科技表（腾讯文档）: https://docs.qq.com/sheet/DV2VQcnBYTHFtcEZF"),
//                    commandList.toList()
//                )
//            )
//            commandList[1] in arrayOf("科研") -> sender.group.sendMessage(
//                MessageBuildUtils.build(
//                    sender,
//                    TextData("科研（腾讯文档）: https://docs.qq.com/doc/DV0ZDclBVaVp5TkVj"),
//                    commandList.toList()
//                )
//            )
//
//        }
//    }

    /**
     * wiki攻略
     */
    suspend fun wiki(commandList: Array<String>, sender: Member, searchAgain: Boolean=true) {
        when {
//            commandList[1] in arrayOf("舰船一图榜", "一图榜", "pve一图榜") -> {
//                val doc = Jsoup.parse(HttpUtils.get("${SEARCH_URL}PVE用舰船综合性能强度榜"))
//                val url = doc.select("div[id='mc_collapse-1']").select("img")[0].attr("src")
//                sender.group.sendMessage(ImagesData(arrayListOf(url)).toMessage(sender))
//            }
            commandList[1] in arrayOf("认知觉醒主线推荐榜", "主线榜", "觉醒榜", "认知觉醒大世界推荐榜", "大世界榜") -> {
                val doc = Jsoup.parse(HttpUtils.get("${SEARCH_URL}认知觉醒推荐榜"))
                val text = getText(commandList)
                val url = doc.select(text).attr("src")
                    .split(Regex("/[\\d]*px"))[0].replace("/thumb", "")
                sender.group.sendMessage(ImagesData(arrayListOf(url)).toMessage(sender))
            }
            commandList[1] in arrayOf("心智1") -> {
                sender.group.sendMessage(
                    ImagesData(arrayListOf("${CommonConfig.emoji_path}/xinzhi_1.png")).toMessage(
                        sender
                    )
                )
            }
            commandList[1] in arrayOf("心智2") -> {
                sender.group.sendMessage(
                    ImagesData(arrayListOf("${CommonConfig.emoji_path}/xinzhi_2.png")).toMessage(
                        sender
                    )
                )
            }
            commandList[1] in arrayOf("科研图纸", "科研", "科研等級") -> {
                try {
                    var startNum: Int
                    var endNum: Int
                    if ("-" in commandList[2]) {
                        val parts = commandList[2].split('-')
                        startNum = parts[0].toInt()
                        endNum = parts[1].toInt()
                    } else{
                        startNum = commandList[2].toInt()
                        endNum = commandList[3].toInt()
                    }

                    if (startNum > endNum) {
                        val t = endNum
                        endNum = startNum
                        startNum = t
                    }
                    if (startNum in 0..35 && endNum in 0..35) {
                        var goldNum = 0
                        var rainbowNum = 0
                        val goldStartNum = keyan_gold_map[startNum]
                        val goldEndNum = keyan_gold_map[endNum]
                        if (goldEndNum != null && goldStartNum != null) {
                            goldNum = goldEndNum - goldStartNum
                        }
                        val rainbowStartNum = keyan_rainbow_map[startNum]
                        val rainbowEndNum = keyan_rainbow_map[endNum]
                        if (rainbowEndNum != null && rainbowStartNum != null) {
                            rainbowNum = rainbowEndNum - rainbowStartNum
                        }
                        sender.group.sendMessage("从" + startNum + "到" + endNum + "所需图纸的金(彩)数量分别为：" + goldNum + "(" + rainbowNum + ")")
                    } else {
                        sender.group.sendMessage("科研等级错误")
                    }
                } catch (e: Exception) {
                    sender.group.sendMessage("解析发生错误\n$e")
                }
            }
            commandList[1] in arrayOf("舰船经验", "经验", "升级经验") -> {
                try {
                    var startNum: Int
                    var endNum: Int
                    if ("-" in commandList[2]) {
                        val parts = commandList[2].split('-')
                        startNum = parts[0].toInt()
                        endNum = parts[1].toInt()
                    } else{
                        startNum = commandList[2].toInt()
                        endNum = commandList[3].toInt()
                    }
                    if (startNum > endNum) {
                        val t = endNum
                        endNum = startNum
                        startNum = t
                    }
                    if (startNum in 1..125 && endNum in 1..125) {
                        var goldNum = 0
                        var rainbowNum = 0
                        val goldStartNum = exp_normal_map[startNum]
                        val goldEndNum = exp_normal_map[endNum]
                        if (goldEndNum != null && goldStartNum != null) {
                            goldNum = goldEndNum - goldStartNum
                        }
                        val rainbowStartNum = exp_rainbow_map[startNum]
                        val rainbowEndNum = exp_rainbow_map[endNum]
                        if (rainbowEndNum != null && rainbowStartNum != null) {
                            rainbowNum = rainbowEndNum - rainbowStartNum
                        }
                        sender.group.sendMessage("舰船从" + startNum + "到" + endNum + "所需的经验(普通船/原生彩)分别为：(" + goldNum + "/" + rainbowNum + ")")
                    } else {
                        sender.group.sendMessage("等级错误")
                    }
                } catch (e: Exception) {
                    sender.group.sendMessage("解析发生错误\n$e")
                }
            }
            commandList[1] in arrayOf("删除缓存","清除缓存") && sender.id in longArrayOf(734929508L, 2516619448L, 897876952L, 1626997525L, 1157509655L)-> {
//                (sender.id == 734929508L || sender.id == 2516619448L)
                println("进入删除...")
                val path = Paths.get("").toAbsolutePath().toString()
                val os = System.getProperty("os.name")
                Wiki.logger.info("os:$os")
                var file:File
                if (commandList.size == 3) {
                    val param3 = commandList[2]
                    if (param3 in SHIP_LIST) {
                        file = if (os != null && os.toString().lowercase().startsWith("windows")) {
                            File("$path\\data\\org.iris.wiki\\out\\ship\\$param3.png")
                        } else {
                            File("$path/data/org.iris.wiki/out/ship/$param3.png")
                        }
                        deleteFile(file)
                    }
                } else if (commandList.size == 4){
                    val param3 = commandList[2]
                    val param4 = commandList[3]
                    if (param3 in SHIP_LIST){
                        file = if (os != null && os.toString().lowercase().startsWith("windows")) {
                            File("$path\\data\\org.iris.wiki\\out\\ship\\$param3($param4）.png")
                        } else {
                            File("$path/data/org.iris.wiki/out/ship/$param3($param4）.png")
                        }
                        deleteFile(file)
                    }
                    if (param3 in EQUIP_LIST){
                        file = if (os != null && os.toString().lowercase().startsWith("windows")) {
                            File("$path\\data\\org.iris.wiki\\out\\equip\\$param3$param4.png")
                        } else {
                            File("$path/data/org.iris.wiki/out/equip/$param3$param4.png")
                        }
                        deleteFile(file)
                    }
                } else {
                    file = if (os != null && os.toString().lowercase().startsWith("windows")) {
                        File("$path\\data\\org.iris.wiki\\out")
                    } else {
                        File("$path/data/org.iris.wiki/out")
                    }
                    deleteFile(file)
                }
                sender.group.sendMessage("删除缓存完成")
            }
            else -> {
                doElse(commandList, sender, searchAgain)
            }
        }
    }

    /**
     * 删除船信息文件
     */
    private fun deleteFile(file:File){
        if (!file.exists()){
            println("文件删除失败,请检查文件路径是否正确")
            return
        }
        val files = file.listFiles()
        if (files?.isNotEmpty() == true) {
            println("开始删除...")
            for (element in files) {
                if (element.isDirectory){
                    deleteFile(element)
                }else {
                    element.delete()
                }
            }
            println("删除完成...")
        }
    }

    /**
     * 处理其他语句
     */
    private suspend fun doElse(commandList: Array<String>, sender: Member, searchAgain: Boolean=true) {
        if (commandList[1] in ALIAS_MAP) {
            commandList[1] = ALIAS_MAP[commandList[1]].toString()
        }
        var result = Checker.check(commandList, sender)
        if (result == null) {
            result = ParserUtils.parse(HttpUtils.get(SEARCH_URL + commandList[1]), commandList.toList())
        }
        if (searchAgain && WikiConfig.command_parse_on && result is SearchData && result.result.isEmpty()) {
            phraseCommand(commandList.joinToString(""), sender)
            return
        }
        val message = MessageBuildUtils.build(sender, result, commandList.toList())
        sender.group.sendMessage(message)
    }

    /**
     * 区分主线和大世界
     */
    private fun getText(commandList: Array<String>): String {
        return if (commandList[1] == "主线榜") {
            "img[alt='认知觉醒主线推荐榜.jpg']"
        } else {
            "img[alt='认知觉醒大世界推荐榜.jpg']"
        }
    }


}
